﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;
using System.Threading;

namespace NewsCrawling
{
    public partial class Form1 : Form
    {
        Thread thread;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            thread = new Thread(new ThreadStart(crawlingStart));
            
            thread.Start();
        }

        private void crawlingStart()
        {
            while (true)
            {
                DataBaseManage db = new DataBaseManage();

                db.openDB();
                String titleData = db.getTitle();
                db.closeDB();
                db.openDB();

                sourceBox.Clear();
                XmlDocument doc = new XmlDocument();
                doc.Load("http://rss.joinsmsn.com/joins_life_list.xml");

                //Console.WriteLine(doc.OuterXml);

                XmlElement rss = doc.DocumentElement;
                XmlElement channel = rss.FirstChild as XmlElement;//<channel>

                //Channel의 자식 중 item이 블로그 내용의 집합

                int count = 0;

                foreach (XmlElement ele in channel.ChildNodes)
                {
                    //sourceBox.AppendText(ele.InnerText);
                    //블로그의 최신글 제목만을 출력 -> 아이템필터링
                    //특정 엘리먼트 검색 == xPath로 처리

                    if (ele.Name == "item")
                    {
                        //Console.WriteLine(title.InnerText);

                        XmlElement title = ele.ChildNodes[0] as XmlElement;

                        if (count == 0)
                        {
                            db.insertrecentlyDB(title.InnerText);
                            count++;
                        }

                        if (title.InnerText.Equals(titleData))
                        {
                            //MessageBox.Show(titleData);
                            break;
                        }

                        sourceBox.AppendText("제목\n");
                        sourceBox.AppendText(title.InnerText);
                        sourceBox.AppendText("\n\n");

                        /*
                        XmlElement desc = ele.ChildNodes[2] as XmlElement;
                        sourceBox.AppendText("본문\n");
                        sourceBox.AppendText(desc.InnerText);
                        sourceBox.AppendText("\n\n");
                        */

                        XmlElement link = ele.ChildNodes[1] as XmlElement;
                        String desc = GetStock(link.InnerText);
                        sourceBox.AppendText("본문\n");
                        sourceBox.AppendText(desc);
                        sourceBox.AppendText("\n");

                        sourceBox.AppendText("링크\n");
                        sourceBox.AppendText(link.InnerText);
                        sourceBox.AppendText("\n\n");


                        XmlElement d_time = ele.ChildNodes[4] as XmlElement;

                        String temp_Time = d_time.InnerText;
                        String[] split_Str = temp_Time.Split('T');

                        String day_Time = split_Str[0] + " ";
                        temp_Time = split_Str[1];
                        String[] split_Time = temp_Time.Split(':');
                        day_Time = day_Time + split_Time[0] + "시 " + split_Time[1] + "분";

                        sourceBox.AppendText("작성일\n");
                        sourceBox.AppendText(day_Time);
                        sourceBox.AppendText("\n\n\n");

                        db.insertDB(title.InnerText, desc, day_Time, link.InnerText);
                    }
                }
                db.closeDB();

                Thread.Sleep(6000);
                MessageBox.Show("실행");
            }
            
        }

        private String GetStock(String strURL)
        {
            //String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7743758&cloc=rss|news|society";
            String tempStr = GetHtmlString(strURL);
            String[] STock = new String[3];
            String[] SplitStr = tempStr.Split(':');
            //int count = 0;

            //return STock;
            //return tempStr;
            return SplitStr[74];
        }
        private String GetHtmlString(String url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String strHtml = reader.ReadToEnd();
            //strHtml = Regex.Replace(strHtml, @"<(.|\n)*?>", String.Empty);
            strHtml = Regex.Replace(strHtml, @"<(.|)*?>", String.Empty);
            //strHtml = strHtml.Replace(" ", "").Replace("\t", "").Replace("//-->", "");
            strHtml = strHtml.Replace("\t", "").Replace("//-->", "");
            String[] str = strHtml.Split(new Char[] {'\n'});
            strHtml = null;
            foreach (String s in str)
            {
                if (s.Trim() != "")
                    strHtml += s + ":";   
            }
            reader.Close();
            response.Close();
            return strHtml;
        }

        private void button_newsData_Click(object sender, EventArgs e)
        {
            String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7731213&cloc=rss|news|society";
            sourceBox.Clear();
            String data = GetStock2(strURL);
            sourceBox.AppendText(data);
        }

        private String GetStock2(String strURL)
        {
            //String strURL = "http://article.joinsmsn.com/news/article/article.asp?total_id=7731213&cloc=rss|news|society";
            String tempStr = GetHtmlString(strURL);
            String[] STock = new String[3];
            String[] SplitStr = tempStr.Split(':');
            
            //return STock;
            //return tempStr;
            return tempStr;
        }

        private void button_db_Click(object sender, EventArgs e)
        {
            thread.Abort();

            /*
            DataBaseManage db = new DataBaseManage();
            db.openDB();
            MessageBox.Show(db.getTitle());
            db.closeDB();
            */
        }

        /*
        private void GetNews()
        {
            WebClient wc = new WebClient();
            wc.Encoding = System.Text.UTF8Encoding.UTF8;
            //String buffer = wc.DownloadString("http://media.daum.net/rss/today/primary/all/rss2.xml");
            //String buffer = wc.DownloadString(String.Format("{0}ig/api?news", _Global.headerURL));
            String buffer = wc.DownloadString("http://rss.joinsmsn.com/joins_money_list.xml");
            
            wc.Dispose();
            StringReader sr = new StringReader(buffer);
            XmlDocument doc = new XmlDocument();
            doc.Load(sr);
            sr.Close();
            //XmlNodeList forecastNodes = doc.SelectNodes("xml_api_reply/news/news_entry");
            XmlNodeList forecastNodes = doc.SelectNodes("rss/channel/item");
            foreach (XmlNode node in forecastNodes)
            {
                String data = node["title"].InnerText;
                String imgURL = node["description"].InnerText;
                sourceBox.AppendText(data);
                //listBoxNew.Items.Add(data);
                //img src
            }
        }
         */
    }
}
